package cn.hamster3.mc.plugin.ball.bungee.util;

import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.ball.common.event.BallActions;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerInfoUpdateEvent;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import org.jetbrains.annotations.NotNull;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;

public final class BallBungeeCordUtils {
    private BallBungeeCordUtils() {
    }

    @NotNull
    public static BallPlayerInfo getPlayerInfo(@NotNull ProxiedPlayer player, boolean online) {
        Server server = player.getServer();
        return new BallPlayerInfo(
                player.getUniqueId(),
                player.getName(),
                server == null ? "connecting" : server.getInfo().getName(),
                BallAPI.getInstance().getLocalServerId(),
                online
        );
    }

    public static void uploadPlayerInfo(@NotNull BallPlayerInfo playerInfo) {
        CoreAPI.getInstance().getExecutorService().execute(() -> {
            try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
                try (PreparedStatement statement = connection.prepareStatement(
                        "REPLACE INTO `hamster_ball_player_info` VALUES(?, ?, ?, ?, ?);"
                )) {
                    statement.setString(1, playerInfo.getUuid().toString());
                    statement.setString(2, playerInfo.getName());
                    statement.setString(3, playerInfo.getGameServer());
                    statement.setString(4, playerInfo.getProxyServer());
                    statement.setBoolean(5, playerInfo.isOnline());
                    statement.executeUpdate();
                }
            } catch (SQLException e) {
                BallAPI.getInstance().getLogger().log(Level.SEVERE, "更新玩家数据时遇到了一个异常", e);
            }
            if (!BallAPI.getInstance().getBallConfig().isGameServerUpdatePlayerInfo()) {
                BallAPI.getInstance().sendRawBallMessage(
                        BallAPI.PLAYER_INFO_CHANNEL,
                        BallActions.BallPlayerInfoUpdate.name(),
                        new BallPlayerInfoUpdateEvent(playerInfo)
                );
            }
        });
    }
}
